package com.gravata.enigma.activities;

import java.sql.SQLException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gravata.enigma.R;
import com.gravata.enigma.model.Regra;

public class RegraActivity extends Activity{

	private TextView nome;
	private Button salvar,cancelar;
	private Context context=this;
	private Regra regra;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regra_screen);

		nome=(TextView) findViewById(R.id.regra_nome);
		salvar=(Button) findViewById(R.id.regra_btn_salvar);
		cancelar=(Button) findViewById(R.id.regra_btn_cancelar);

		regra=(Regra) getIntent().getSerializableExtra("regra");
		if(regra!=null){
			nome.setText(regra.getName());
		}else{
			regra=new Regra();
			regra.setOrdem(TelaInicial.regras.size()+1);
			regra.setProfile(TelaInicial.profile);
		}
		cancelar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				setResult(0);
				finish();
			}
		});

		salvar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {

				if(!validate()){
					Toast.makeText(context, R.string.nome_obrigatorio, Toast.LENGTH_LONG).show();
					return;
				}else{
					salvar();
				}

			}
		});

	}

	private boolean validate(){

		return nome.getText().length()!=0;

	}

	private void salvar(){
		try {
			regra.setName(nome.getText().toString());

			TelaInicial.repositorioRegra.inserirOuAtualizar(regra);

			getIntent().putExtra("regra", regra);
			setResult(1, getIntent());
			Toast.makeText(context, R.string.salvo_sucesso, Toast.LENGTH_LONG).show();

		} catch (SQLException e) {
			e.printStackTrace();
			setResult(0, getIntent());
			Log.e("SALVAR", e.getMessage());
			Toast.makeText(context, R.string.erro_salvar, Toast.LENGTH_LONG).show();
		}

		finish();
	}

}
